package base;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j(topic = "c.interrupt")
public class TestInterrupt {
    public static void main(String[] args) throws InterruptedException {
        test2();
    }

    private static void test2() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            while (true){
                boolean interrupted = Thread.currentThread().isInterrupted();
                if (interrupted) {
                    log.debug("interrupted..退出循环");
                    break;
                }
            }
        }, "t1");
        t1.start();
        TimeUnit.SECONDS.sleep(1);
        log.debug("interrupt");
        t1.interrupt();
    }

    //睡眠的线程被打断会抛出对应异常，对异常不作处理则该线程被唤醒后会从try-catch块后继续执行
    private static void test1() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            log.debug("sleep");
            try {
                TimeUnit.SECONDS.sleep(2);
                log.debug("wake up and running");
            } catch (InterruptedException e) {
                log.debug("interrupted");
//                e.printStackTrace();
                log.debug("打断标记{}", Thread.currentThread().isInterrupted());
            }
            log.debug("do next things");
        }, "t1");
        t1.start();
        TimeUnit.SECONDS.sleep(1);
        log.debug("interrupt");
        t1.interrupt();
        log.debug("打断标记{}",t1.isInterrupted());
    }

}
